import os
import sys
import time
from pathlib import Path

# 设置编码环境
os.environ['PGCLIENTENCODING'] = 'UTF8'
os.environ['PYTHONIOENCODING'] = 'utf-8'

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager

# 添加一个全局变量来跟踪中间件调用
debug_middleware_called = False

# 导入配置和路由
from app.core.database import engine, Base
from app.core.config import settings
from app.core.logging import setup_logging, get_logger
from app.api.v1.api import api_router
from app.middleware.loguru_middleware import setup_loguru_middleware
from app.middleware.exception_middleware import setup_exception_handlers
from app.middleware.request_validation_middleware import setup_request_validation_middleware
from scripts.init_email import init_email_system

# 获取模块级别的logger
app_logger = get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    try:
        # 设置loguru日志系统
        config = setup_logging(
            environment=getattr(settings, 'ENVIRONMENT', 'development'),
            app_name=getattr(settings, 'PROJECT_NAME', 'fastapi-app'),
            log_dir=getattr(settings, 'LOG_DIR', './logs')
        )
        app_logger.info("✅ Loguru日志系统初始化成功")
        
        # 注意：Loguru中间件已经在应用创建时添加，无需在此处重复添加
        
    except Exception as e:
        # 如果loguru初始化失败，使用备用方案
        import sys
        print(f"❌ Loguru初始化失败: {e}", file=sys.stderr)
    
    # 创建数据库表（如果不存在）
    try:
        Base.metadata.create_all(bind=engine)
        app_logger.info("✅ 数据库表创建成功")
    except Exception as e:
        app_logger.error(f"❌ 数据库表创建失败: {e}")
    
    # 初始化邮件系统
    try:
        init_email_system()
        app_logger.info("✅ 邮件系统初始化成功")
    except Exception as e:
        app_logger.error(f"❌ 邮件系统初始化失败: {e}")
    
    yield
    
    # 关闭时
    app_logger.info("🛑 应用正在关闭...")


# 创建FastAPI应用
app = FastAPI(
    title=getattr(settings, 'PROJECT_NAME', 'FastAPI Platform'),
    version=getattr(settings, 'VERSION', '1.0.0'),
    description=getattr(settings, 'DESCRIPTION', 'A modern FastAPI platform'),
    debug=getattr(settings, 'DEBUG', False),
    docs_url=getattr(settings, 'DOCS_URL', '/docs'),
    redoc_url=getattr(settings, 'REDOC_URL', '/redoc'),
    openapi_url=getattr(settings, 'OPENAPI_URL', '/openapi.json'),
    lifespan=lifespan,
    # API文档配置
    openapi_tags=[
        {
            "name": "🔐 认证授权",
            "description": "用户登录、注册、JWT令牌管理等认证相关功能"
        },
        {
            "name": "👥 用户管理", 
            "description": "用户信息的增删改查、用户状态管理"
        },
        {
            "name": "🎭 角色管理",
            "description": "系统角色的创建、分配和管理"
        },
        {
            "name": "🔑 权限管理",
            "description": "权限的定义、分配和验证"
        },
        {
            "name": "🔥 热点数据",
            "description": "各大平台热点数据的获取和管理"
        },
        {
            "name": "🧠 LLM模型",
            "description": "LLM模型调用、对话管理等AI相关功能"
        },
        {
            "name": "📊 仪表盘",
            "description": "数据统计、图表展示、系统监控"
        },
        {
            "name": "🕷️ 爬虫任务",
            "description": "网页爬取任务的创建、调度和管理"
        },
        {
            "name": "系统",
            "description": "系统基础功能和健康检查"
        }
    ],
    contact={
        "name": "FastAPI Platform",
        "email": "admin@example.com"
    },
    license_info={
        "name": "MIT License",
        "url": "https://opensource.org/licenses/MIT"
    }
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=getattr(settings, 'BACKEND_CORS_ORIGINS', ["*"]),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 设置请求验证中间件
setup_request_validation_middleware(app)

# 设置Loguru中间件（在应用创建时添加，而不是在生命周期中添加）
setup_loguru_middleware(app)

# 设置异常处理器
setup_exception_handlers(app)

# 注册API路由
try:
    app.include_router(api_router)
    app_logger.info("✅ API路由注册成功")
except Exception as e:
    app_logger.error(f"❌ API路由注册失败: {e}")
    # 创建空的API路由作为fallback
    from fastapi import APIRouter
    fallback_router = APIRouter(prefix="/api/v1")
    app.include_router(fallback_router)
    app_logger.warning("⚠️ 使用空的fallback路由")

# 简化的请求日志中间件（将被loguru中间件替代）
@app.middleware("http")
async def simple_request_logger(request, call_next):
    """简单的请求日志（兼容性中间件）"""
    start_time_req = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time_req

    # 只记录非静态资源的请求
    if not request.url.path.startswith(('/static', '/favicon')):
        app_logger.info(
            "HTTP请求",
            method=request.method,
            path=request.url.path,
            status_code=response.status_code,
            duration_seconds=round(process_time, 3),
            client_ip=request.client.host if request.client else "unknown"
        )

    response.headers["X-Process-Time"] = str(process_time)
    return response


@app.get("/", tags=["系统"])
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用 {getattr(settings, 'PROJECT_NAME', 'FastAPI Platform')}",
        "version": getattr(settings, 'VERSION', '1.0.0'),
        "description": getattr(settings, 'DESCRIPTION', 'A modern FastAPI platform'),
        "status": "running",
        "environment": getattr(settings, 'ENVIRONMENT', 'development'),
        "docs_url": getattr(settings, 'DOCS_URL', '/docs') if not getattr(settings, 'is_production', False) else None
    }


@app.get("/health", tags=["系统"])
async def health_check():
    """健康检查端点"""
    import time
    from app.core.database import engine
    from app.core.db_utils import DatabaseMetrics
    from sqlalchemy import text
    
    try:
        # 检查数据库连接
        with engine.connect() as conn:
            conn.execute(text("SELECT 1"))
        
        # 获取连接池状态
        pool_status = DatabaseMetrics.get_connection_pool_status(engine)
        
        return {
            "status": "healthy",
            "timestamp": time.time(),
            "version": getattr(settings, 'VERSION', '1.0.0'),
            "environment": getattr(settings, 'ENVIRONMENT', 'development'),
            "database": {
                "status": "connected",
                "pool": pool_status
            },
            "features": {
                "api_documentation": "enabled",
                "exception_handling": "enabled", 
                "request_validation": "enabled",
                "database_optimization": "enabled"
            }
        }
    except Exception as e:
        return {
            "status": "unhealthy",
            "timestamp": time.time(),
            "error": str(e),
            "database": {
                "status": "disconnected"
            }
        }

# 异常处理已通过中间件统一管理


def main():
    """主函数 - 启动应用"""
    try:
        app_logger.info(f"🚀 启动 {getattr(settings, 'PROJECT_NAME', 'FastAPI Platform')} v{getattr(settings, 'VERSION', '1.0.0')}")
        app_logger.info(f"🌍 环境: {getattr(settings, 'ENVIRONMENT', 'development')}")

        import uvicorn
        import logging
        
        # 配置Uvicorn访问日志
        access_logger = logging.getLogger("uvicorn.access")
        access_logger.setLevel(logging.INFO)
        
        uvicorn.run(
            "main:app",
            host=getattr(settings, 'HOST', '127.0.0.1'),
            port=getattr(settings, 'PORT', 8000),
            reload=False,
            log_level="info",  # 设置为warning减少uvicorn日志
            access_log=True,
            use_colors=True
        )

    except KeyboardInterrupt:
        app_logger.info("👋 收到中断信号，正在关闭应用...")
    except Exception as e:
        app_logger.error(f"❌ 应用启动失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()